import {
    AfterViewInit,
    Component,
    ElementRef,
    Input,
    OnDestroy,
    OnInit,
    QueryList,
    Renderer2,
    ViewChild,
    ViewChildren
} from '@angular/core';

export interface ImageSlider {
    imgUrl: string;
    link: string;
    caption: string;
}

@Component({
    selector: 'app-image-slider',
    templateUrl: './image-slider.component.html',
    styleUrls: ['./image-slider.component.css']
})
export class ImageSliderComponent implements OnInit, AfterViewInit, OnDestroy {
    @Input() private sliders: ImageSlider[] = [];
    @Input() private sliderHeight = '160px';
    @Input() private intervalBySeconds = 2;
    //
    @ViewChild('imageSlider', { static: true }) private imgSliderRef: ElementRef;
    @ViewChildren('img') private imgs: QueryList<ElementRef>;
    private selectedIndex = 0;
    private intervalId;
    //
    public constructor(private rd2: Renderer2) {}
    //
    public ngOnInit() {
        console.log(this.imgSliderRef);
    }
    public ngAfterViewInit() {
        this.intervalId = setInterval(() => {
            this.rd2.setProperty(
                this.imgSliderRef.nativeElement,
                'scrollLeft',
                (this.getIndex(++this.selectedIndex) *
                    this.imgSliderRef.nativeElement.scrollWidth) /
                    this.sliders.length
            );
        }, this.intervalBySeconds * 1000);
    }

    public ngOnDestroy() {
        clearInterval(this.intervalId);
    }

    private handleScroll(ev) {
        const ratio = ev.target.scrollLeft / (ev.target.scrollWidth / this.sliders.length);
        this.selectedIndex = Math.round(ratio);
    }

    /**
     * 获取当前图片的index
     * @param idx  索引
     */
    private getIndex(idx: number): number {
        // 超过数组的长度 则等于数组长度 也就是最后一张
        return idx >= 0
            ? idx % this.sliders.length
            : this.sliders.length - (Math.abs(idx) % this.sliders.length);
    }
}
